/**
 * 84. 柱状图中最大的矩形
 * https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
 */

/**
 * @param {number[]} heights
 * @return {number}
 */
function largestRectangleArea(heights) {
  const stack = new Array(heights.length);
  let top = -1;
  const lowersLeft = new Array(heights.length);
  for (let i = 0; i < heights.length; i += 1) {
    while (top >= 0 && heights[stack[top]] >= heights[i]) {
      top -= 1;
    }
    if (top >= 0) {
      lowersLeft[i] = stack[top];
    } else {
      lowersLeft[i] = -1;
    }
    top += 1;
    stack[top] = i;
  }
  let max = 0;
  top = -1;
  for (let i = heights.length - 1; i >= 0; i -= 1) {
    while (top >= 0 && heights[stack[top]] >= heights[i]) {
      top -= 1;
    }
    let higher;
    if (top >= 0) {
      higher = stack[top];
    } else {
      higher = heights.length;
    }
    max = Math.max(max, heights[i] * (higher - lowersLeft[i] - 1));
    top += 1;
    stack[top] = i;
  }
  return max;
}

console.log(largestRectangleArea([2, 1, 5, 6, 2, 3]) === 10);
console.log(largestRectangleArea([2, 4]) === 4);
console.log(largestRectangleArea([0, 9]) === 9);
